package com.zzj.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zzj.bean.LoginHistory;
import com.zzj.bean.TabLogin;
import com.zzj.bean.TableEmployee;
import com.zzj.config.VerifyCodeUtils;
import com.zzj.service.LoginHistoryService;
import com.zzj.service.TabLoginService;
import com.zzj.service.TableEmployeeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * InnoDB free: 8192 kB 前端控制器
 * </p>
 *
 * @author 花
 * @since 2022-03-04
 */
@RestController
@RequestMapping("/login")
@Api
@SessionAttributes
@CrossOrigin
public class TabLoginController {

    @Autowired
    private TabLoginService loginService;
    @Autowired
    private TableEmployeeService employeeService;
    @Autowired
    private LoginHistoryService historyService;

    @GetMapping("/login")
    @ApiOperation("登录")
    public TableEmployee login(String username, String password, HttpServletRequest request){
        QueryWrapper<TabLogin> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        wrapper.eq("psw",password);
        wrapper.eq("lstatus","1");
        List<TabLogin> list = loginService.list(wrapper);
        if (list.size() == 1){
            HttpSession session = request.getSession();
            session.setAttribute("login",list.get(0));
            TableEmployee employee = employeeService.getById(list.get(0).getUid());
            session.setAttribute("employee",employee);
            session.setAttribute("uid",list.get(0).getUid());
            LoginHistory loginHistory = new LoginHistory();
            loginHistory.setLhstatus("1");
            loginHistory.setLogintime(LocalDateTime.now());
            loginHistory.setUid(list.get(0).getUid());
            historyService.save(loginHistory);
            return employee;
        }
        return null;
    }

    @GetMapping("/logout/{uid}")
    @ApiOperation("退出")
    public boolean logout(HttpServletRequest request,@PathVariable("uid") String uid){
        LoginHistory loginHistory = new LoginHistory();
        loginHistory.setUid(uid);
        loginHistory.setLhstatus("0");
        loginHistory.setLogintime(LocalDateTime.now());
        System.out.println("loginHistory = " + loginHistory);
        historyService.save(loginHistory);
        request.getSession().invalidate();
        return true;
    }

    @GetMapping("getCode")
    @ApiOperation("生成验证码")
    public String generatorCode(){
        try {
            return VerifyCodeUtils.generatorCode();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}

